package com.faxsun.service.handlers;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.broadleafcommerce.common.exception.ServiceException;
import org.broadleafcommerce.openadmin.dto.Entity;
import org.broadleafcommerce.openadmin.dto.PersistencePackage;
import org.broadleafcommerce.openadmin.server.service.persistence.PersistenceManager;
import org.broadleafcommerce.openadmin.server.service.persistence.PersistenceManagerEventHandlerAdapter;
import org.broadleafcommerce.openadmin.server.service.persistence.PersistenceManagerEventHandlerResponse;

import com.faxsun.common.currency.domain.FSCurrencyRate;
import com.faxsun.tools.EntityHelper;

/**
 * 汇率更新hook，可以CARD执行前后进行的操作
 * @author zhaoteng.song@faxsun.com
 *
 */
public class UpdateFSCurrencyHandler extends
		PersistenceManagerEventHandlerAdapter {

	@SuppressWarnings("unused")
	private static final Log LOG = LogFactory
			.getLog(UpdateFSCurrencyHandler.class);

	@Override
	public PersistenceManagerEventHandlerResponse preUpdate(
			PersistenceManager persistenceManager,
			PersistencePackage persistencePackage) throws ServiceException {

		Entity entity = persistencePackage.getEntity();

		boolean isFSCurrencyRate = EntityHelper.isTargetClass(entity,
				FSCurrencyRate.class);

		if (isFSCurrencyRate) {

			String date = EntityHelper.getFieldFromProperties(entity, "date");
			if (date != null && !date.isEmpty()) {
				return new PersistenceManagerEventHandlerResponse()
						.withStatus(PersistenceManagerEventHandlerResponse.PersistenceManagerEventHandlerResponseStatus.HANDLED);
			}

		}

		return new PersistenceManagerEventHandlerResponse()
				.withStatus(PersistenceManagerEventHandlerResponse.PersistenceManagerEventHandlerResponseStatus.NOT_HANDLED);

	}

	@Override
	public PersistenceManagerEventHandlerResponse preAdd(
			PersistenceManager persistenceManager,
			PersistencePackage persistencePackage) throws ServiceException {

		Entity entity = persistencePackage.getEntity();

		boolean isFSCurrencyRate = EntityHelper.isTargetClass(entity,
				FSCurrencyRate.class);

		if (isFSCurrencyRate) {

			String date = EntityHelper.getFieldFromProperties(entity, "date");
			if (date == null || date.isEmpty()) {
				date = EntityHelper.getCurrentTime();
				EntityHelper.setFieldFromProperties(entity, "date", date);
				persistencePackage.setEntity(entity);
			}

			return new PersistenceManagerEventHandlerResponse()
					.withStatus(PersistenceManagerEventHandlerResponse.PersistenceManagerEventHandlerResponseStatus.HANDLED);
		}

		return new PersistenceManagerEventHandlerResponse()
				.withStatus(PersistenceManagerEventHandlerResponse.PersistenceManagerEventHandlerResponseStatus.NOT_HANDLED);
	}
}
